
// 获取四个子元素
const doms = {
    carousel:document.querySelector(".imglist"),
    arrowRight:document.querySelector(".right-button"),
    arrowLeft:document.querySelector(".left-button"),
    bottomDots:document.querySelectorAll(".bottom-dots span")
}
const itemNum=doms.bottomDots.length
/**
 * 无缝轮播 增加前后两个节点
 */
const init=()=>{
    
    const fristNode = doms.carousel.firstElementChild.cloneNode(true)
    const lastNode = doms.carousel.lastElementChild.cloneNode(true)
    doms.carousel.appendChild(fristNode)
    doms.carousel.insertBefore(lastNode, doms.carousel.firstElementChild)
    lastNode.style.marginLeft="-100%"
}
init()
console.log(doms.bottomDots);
let curIndex=0;
/**
 * 滚动到指定区域
 * @param {nuber} index 
 */
const carouselMoveTo=(index)=>{
const {carousel,bottomDots} = doms
   carousel.style.transform=`translateX(-${index*100}%)`
   carousel.style.transition=`transform 0.5s`
   console.log(bottomDots);
   bottomDots.forEach((element,i) => {
    index===i?element.classList.add("active"): element.classList.remove("active")
   });
   curIndex=index
}
carouselMoveTo(0)
// 给下方的圆点绑定事件
doms.bottomDots.forEach((elem,i)=>{
    elem.onclick=()=>{
        carouselMoveTo(i)
    }
})
const rightClickMoveTo=()=>{
    if(curIndex===itemNum-1){
        doms.carousel.style.transition="none"
        doms.carousel.style.transform=`translateX(100%)`
        doms.carousel.clientWidth;//读取dom几何信息触发回流，强制渲染一帧
        carouselMoveTo(0)
    }else{
        carouselMoveTo(curIndex+1)
    }
}
const leftClickMoveTo=()=>{
    if(curIndex===0){
        doms.carousel.style.transition="none"
        doms.carousel.style.transform=`translateX(-${(itemNum)*100}%)`
        doms.carousel.clientWidth;//读取dom几何信息触发回流，强制渲染一帧
        carouselMoveTo(itemNum-1)
    }else{
        carouselMoveTo(curIndex-1)
    }
}
doms.arrowRight.onclick=rightClickMoveTo
doms.arrowLeft.onclick=leftClickMoveTo



